﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Collections;
using System.Reflection;
using System.Windows.Forms;

namespace DataAccess
{
    public static class DataTableConverter
    {
        public static ArrayList GetObjects(DataTable table, Type type)
        {

            ArrayList list = new ArrayList();
            if(table.Rows.Count>0)
            foreach (DataRow row in table.Rows)
            {
                Object target = Activator.CreateInstance(type);

                //Type myType = typeof();

                System.Reflection.PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);

                foreach (DataColumn column in table.Columns)
                {
                    foreach (System.Reflection.PropertyInfo property in properties)
                    {
                        if (properties.GetType() != typeof(ArrayList))
                        {
                            Bind(column.ColumnName, target, property, row[column]);
                        }
                    }
                }

                //DataColumnAttribute.Bind(row, table.Columns, target);
                list.Add(target);
            }
            return list;
        }

        private static void Bind(string columnName, object target, PropertyInfo field, object value)
        {

            if (field.Name == columnName)
            {
                try
                {
                    field.SetValue(target, value, null);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

            }

        }
    }
}
